package edu.hunan.cxb18.error;

import edu.hunan.cxb18.error.impl.CommonErrorImpl;
import edu.hunan.cxb18.error.impl.UserException;
import edu.hunan.cxb18.result.CommonTypeResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author AuthorName
 * @create 2020-04-23 13:44
 */
public class BaseController {
    // 定义 exceptionhandler 解决未被 controller 层吸收的 exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex){

        Map<String, Object> responseData = new HashMap<>();

        if(ex instanceof UserException){
            UserException userException = (UserException) ex;
            responseData.put("errCode", userException.getErrCode());
            responseData.put("errMsg", userException.getErrMsg());
        }else{
            responseData.put("errCode", CommonErrorImpl.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg", CommonErrorImpl.UNKNOWN_ERROR.getErrMsg());
        }

        return CommonTypeResult.creat(responseData, "fail");
    }
}
